<template lang="html">
 <div class="main">
   <panel title="购买麻精药品预警" class="panel">
     <div class="body"  v-loading="loading"
         element-loading-text="地图加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="transparent">
       <div class="chart" id="warn-bug-map">
       </div>
       <div class="map-info">
           <div class="map-message" v-if="activePerson">
               <div class="msg-img">
                 <img :src="`/static/${activePerson.headImg}.jpg`">
               </div>
               <div class="msg-item" >
                   <div style="position: relative;">姓名：{{activePerson.name}}</div>
                   <div>身份证：{{activePerson.id}}</div>
                   <div style="width: 210px;">地址：{{activePerson.place}}</div>
               </div>
           </div>
           <transition-group name="list" tag="p">
            <div class="map-message2" v-for="(item, i) in infos" :key="i">
                <div class="msg-img">
                  {{item.index + 1}}
                </div>
                <div class="msg-item">
                    <div style="position: relative;">{{item.store.store}}<span @click="infos.splice(i, 1)" style="cursor: pointer;position: absolute; right: -2px; top: -10px;">x</span></div>
                    <div>药店法人：{{item.store.legalPerson}}</div>
                    <div>药店地址：{{item.store.place}}</div>
                    <div>监管：{{item.store.supervisor.drugSupervisor}} {{item.store.supervisor.drugSupervisorTelephone}}</div>
                </div>
            </div>
          </transition-group>
       </div>
     </div>
   </panel>
   <panel title="预警信息" class="panel right">
       <ul class="table">
         <li :class="{'active': active === item.id, 'blink': item.new}" v-for="(item, index) in data" :key="index" @click="isrun = false;showRun(item)">
          <div>{{item.name}}购买麻精药品超额预警</div> <span>{{item.event[item.event.length - 1].time}}</span>
         </li>
       </ul>
   </panel>
 </div>
</template>

<script>
import { lazyAMapApiLoaderInstance } from 'vue-amap';
import panel from '@/components/panel.vue';
import fetchWarnBuy from './fetchWarnBuy';
import fetchDistrictInfo from './fetchDistrictInfo';
// import { fetchWarnBuy, fetchDistrictInfo } from '@/common/api';
export default {
  data () {
    return {
      map: null,
      pathSimplifierIns: null,
      infoWindow: null,
      loading: true,
      markers: [], // 坐标点
      active: 0,
      start: 0,
      isrun: true,
      infos: [],
      districts: [],
      data: []
    };
  },
  components: {
    panel
  },
  computed: {
    activePerson () {
      return this.data.find(d => d.id === this.active);
    }
  },
  methods: {
    rnd (n, m) {
      return Math.floor(Math.random() * (m - n + 1) + n);
    },
    toRad (d) {
      return d * Math.PI / 180;
    },
    addTime (t, h) {
      let time = new Date(t + h * 1000 * 60 * 60);
      let fm = n => {
        return n < 10 ? `0${n}` : n;
      };
      return fm(time.getHours()) + ':' + fm(time.getMinutes());
    },
    toM (start, end) { // lat为纬度, lng为经度, 一定不要弄错
      let dis = 0;
      let radLat1 = this.toRad(start[0]);
      let radLat2 = this.toRad(end[0]);
      let deltaLat = radLat1 - radLat2;
      let deltaLng = this.toRad(start[1]) - this.toRad(end[1]);
      dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
      return dis * 6378137;
    },
    showMsg (d, index) {
      if (!this.map) {
        return;
      }
      let msg = [];
      msg.push(`<div style="width: 350px;margin: 0px; padding: 0px;"><b>${d.name}</b><br/><hr>`);
      for (let i = index; i >= 0; i--) {
        let e = d.event[i];
        msg.push(`<div style="font-size: 13px; color: #666;"><b>${e.time}</b>在<b style="color: #333;">${e.place}</b>购买${e.num}盒${e.name}！</div>`);
      }
      msg.push('</div>');
      this.infoWindow.setContent(msg.join(''));
      this.infoWindow.open(this.map, d.event[index].position);
    },
    showRun (item) {
      if (!this.map) {
        return;
      }
      if (this.active === item.id) {
        return;
      }
      this.active = item.id;
      let d = this.data.find(d => d.id === item.id);
      let p = d.event.map(e => e.position);
      this.map.remove(this.markers);
      this.markers = [];
      this.infos = [];
      this.infoWindow.close();
      this.setMap(d, p);
    },
    setMap (d, positions) {
      if (!this.map) {
        return;
      }
      positions.forEach((p, index) => {
        let marker = new AMap.Marker({
          map: this.map,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b' + (this.markers.length + 1) + '.png',
          position: p
        });
        marker.on('click', () => {
          this.showMsg(d, index);
          this.isrun = false;
          if (this.infos.findIndex(n => n.name === d.event[index].store) === -1) {
            this.infos.push({name: d.event[index].store, store: d.event[index], index: index});
          }
        });
        this.markers.push(marker);
      });
      // 轨迹 走道路
      this.runByRoad(positions);
    },
    runByRoad (thisRun) {
      if (!this.map) {
        return;
      }
      // 运行道路
      var driving = new AMap.Driving({
        // map: this.map
      });
      let start = thisRun[0];
      let end = thisRun[thisRun.length - 1];
      let waypoints = [];
      if (thisRun.length > 2) {
        waypoints = thisRun.filter((d, i) => i > 0 && i < (thisRun.length - 1));
      }
      // 根据起终点经纬度规划驾车导航路线
      driving.search(start, end, {
        waypoints: waypoints
      }, (status, result) => {
        // 未出错时，result即是对应的路线规划方案
        if (status === 'complete') {
          let roads = [];
          result.routes[0].steps.forEach(s => s.tmcs.forEach(t => {
            roads.push(...t.polyline.split(';').map(tt => tt.split(',')));
          }));
          // 道路
          this.setRun(roads, result.routes[0].distance);
        } else {
          // 直线
          this.setRun(thisRun);
        }
      });
    },
    setRun (thisRun, m = 0) {
      if (!this.map) {
        return;
      }
      AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], (PathSimplifier, $) => {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！');
          return;
        }
        if (!this.pathSimplifierIns) {
          this.pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            map: this.map, // 所属的地图实例
            getPath: function (pathData, pathIndex) {
              return pathData.path;
            },
            getHoverTitle: (pathData, pathIndex, pointIndex) => {
              // console.log(pathData, pathIndex, pointIndex);
              // if (pointIndex >= 0) {
              //   return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length;
              // }
              // return pathData.name + '，点数量' + pathData.path.length;
              return '';
            },
            renderOptions: {
              pathLineStyle: {
                dirArrowStyle: true
              },
              getPathStyle: function (pathItem, zoom) {
                let color = '#C8AA3E';
                let lineWidth = Math.round(4 * Math.pow(1.1, zoom - 3));
                return {
                  pathLineStyle: {
                    strokeStyle: color,
                    lineWidth: lineWidth
                  },
                  pathLineSelectedStyle: {
                    lineWidth: lineWidth + 2
                  },
                  pathNavigatorStyle: {
                    fillStyle: color
                  }
                };
              },
              renderAllPointsIfNumberBelow: 100 // 绘制路线节点，如不需要可设置为-1
            }
          });
        }

        // 设置数据
        this.pathSimplifierIns.setData([{
          name: '路线0',
          path: thisRun
        }]);
        if (m === 0) {
          thisRun.forEach((n, i) => {
            if (i > 0) {
              m += this.toM(thisRun[i - 1], n);
            }
          });
        }
        // 对第一条线路（即索引 0）创建一个巡航器
        var navg1 = this.pathSimplifierIns.createPathNavigator(0, {
          loop: false, // 循环播放
          speed: m / 6 * 3.8, // 巡航速度，单位千米/小时
          pathNavigatorStyle: {
            // autoRotate: false, // 禁止调整方向
            'content': 'circle',
            pathLinePassedStyle: {
              'lineWidth': 5,
              'strokeStyle': '#AF9739',
              'borderWidth': 1,
              'borderStyle': '#AF9739',
              'dirArrowStyle': false
            },
            width: 20,
            height: 20,
            // content: PathSimplifier.Render.Canvas.getImageContent('./imgs/car-front.png', onload, onerror),
            strokeStyle: '#ffffff',
            fillStyle: '#B83763'
          }
        });
        let center_ = this.map.getCenter();
        navg1.on('move', (d) => {
          this.map.setCenter(navg1.getPosition());
        });
        navg1.on('pause', () => {
          setTimeout(_ => {
            console.log([center_.lng, center_.lat - 0.1]);
            this.map.setCenter([center_.lng, center_.lat + 0.1]);
            this.map.setZoom(this.map.getZoom() - 0.8);
          }, 500);
        });
        setTimeout(_ => {
          navg1.start();
          this.runShowMsg(0);
        }, 1000);
      });
    },
    runShowMsg (index) {
      if (!this.map) {
        return;
      }
      clearTimeout(window.timeout);
      let d = this.data.find(d => d.id === this.active);
      let l = d.event.length;
      if (index >= l) {
        return;
      }
      this.showMsg(d, index);
      let self = this;
      window.timeout = setTimeout(_ => {
        if (self && !self._isDestroyed) {
          this.runShowMsg(++index);
        }
      }, 6000 / (l - 1));
    },
    addData2List ({person, drugStores}) {
      let fm = n => {
        return n < 10 ? `0${n}` : n;
      };
      let now = new Date();
      let h = now.getHours();
      let m = now.getMinutes();
      let item = {
        id: person.idcard,
        new: this.data.length > 0,
        name: person.name,
        place: person.place,
        headImg: person.headImg,
        event: drugStores.map((d, i) => {
          return {
            name: '酚麻美敏片',
            num: 1,
            store: d.name,
            legalPerson: d.legalPerson,
            supervisor: this.districts.find(s => s.name === d.distric),
            time: `${fm(h - (drugStores.length - i))}:${fm(m)}`,
            place: d.place,
            position: d.position.split(',')
          };
        })
      };
      this.data.splice(0, 0, item);
      setTimeout(_ => {
        if (this.isrun) {
          this.showRun(item);
        }
      }, 2000);
      setTimeout(_ => {
        this.data.find(d => d.id === item.id).new = false;
      }, 3000);
    },
    loadData () {
      // return fetchWarnBuy({start: this.start, size}).then(res => {
      let res = fetchWarnBuy;
      this.start = this.start % res.data.length;
      if (res.data && res.data.length > 1) {
        this.addData2List(res.data[this.start]);
        this.start++;
        let self = this;
        setTimeout(_ => {
          if (self && !self._isDestroyed) {
            this.loadData();
          }
        }, 20000);
      }
      // }).catch(err => {
      //   console.log(err);
      // });
    }
  },
  mounted () {
    setTimeout(_ => {
      lazyAMapApiLoaderInstance.load().then(() => {
        this.map = new AMap.Map('warn-bug-map', {
          features: ['bg', 'road'],
          center: [121.59996, 31.197646],
          zooms: [9, 18], // 设置地图级别范围
          zoom: 9,
          resizeEnable: false,
          mapStyle: 'amap://styles/7fbd2932c63ed9235ab53a7a6fc0db1d'
        });
        this.map.on('complete', () => {
          this.loading = false;
        });
        setTimeout(_ => {
          this.loading = false;
        }, 200);
        this.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        this.map.addControl(new AMap.Scale());
        // // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
        // this.map.addControl(new AMap.OverView({isOpen: true}));
        // fetchDistrictInfo().then(res => {
        let res = fetchDistrictInfo;
        this.districts = res.data;
        this.loadData();
        let d = this.data[0];
        this.active = d.id;
        let p = d.event.map(e => e.position);
        this.setMap(d, p);
        // }).catch(err => {
        //   console.log(err);
        // });
      });
    }, 700);
  },
  beforeDestroy () {
    if ('destroy' in this.map) {
      console.log('注销..............');
      this.map.destroy();
      this.map = false;
    }
  }
};
</script>

<style lang="css" scoped>
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  .panel {
    margin-left: 20px;
    width: 100%;
    height: 100%;
    .body {
      width: 100%;
      height: 100%;
      padding: 5px 10px;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
      .chart {
        width: 100%;
        height: 100%;
      }
      .map-info {
        position: absolute;
        left: 10px;
        top: 0px;
        .map-message {
          font-size: 14px;
          color: #fff;
          margin-top: 5px;
          display: flex;
          flex-direction: row;
          align-items: stretch;
          border: 1px solid rgba(32,117,194,.8);
          border-top-right-radius: 5px;
          border-bottom-right-radius: 5px;
          .msg-img {
            left: 0px;
            background-color: #fff;
            width: 80px;
            display: flex;
            align-items: center;
            img {
              width: 80px;
            }
          }
          .msg-item {
            background-color: rgba(32,117,194,.8);
            padding: 5px;
            text-align: left;
          }
        }
        p {
          margin: 0px;
          padding: 0px;
          z-index: 0;
        }
        .map-message2 {
          font-size: 14px;
          color: #fff;
          margin-top: 5px;
          display: flex;
          flex-direction: row;
          align-items: stretch;
          width: 250px;
          border: 1px solid rgba(32,117,194,.8);
          border-top-right-radius: 5px;
          border-bottom-right-radius: 5px;
          .msg-img {
            font-size: 30px;
            color: rgba(200,10,10,.8);
            background-color: inherit;
            width: 50px;
            height: auto;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .msg-item {
            width: 200px;
            max-width: 200px;
            background-color: rgba(32,117,194,.8);
            padding: 5px;
            text-align: left;
          }
        }
      }
    }
    .table {
      margin: 0px;
      padding: 20px;
      height: 95%;
      overflow-y: auto;
      li {
        cursor: default;
        padding-left: 5px;
        line-height: 40px;
        height: 40px;
        text-align: left;
        border-bottom: 1px solid #eee;
        font-size: 16px;
        display: flex;
        flex-direction: row;
        align-items: stretch;
        justify-content: space-between;
        div {
          white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
        }
        span {
          color: #999; font-size: 12px;margin-right: 10px;
        }
      }
      li:hover {
        background-color: #999;
        color: #fff;
        span {
          color: #f1f1f1;
        }
      }
      .active {
        background-color: #999;
        color: #fff;
        span {
          color: #f1f1f1;
        }
      }
    }
  }
  .panel:first-child {
    margin-left: 0px;
  }
  .right {
    width: 40%;
    height: 100%;
  }
}

/* 定义keyframe动画，命名为blink */
@keyframes blink{
  0%{opacity: 1;}
  100%{opacity: 0;}
}
/* 添加兼容性前缀 */
@-webkit-keyframes blink {
    0% { opacity: 1; }
    100% { opacity: 0; }
}
@-moz-keyframes blink {
    0% { opacity: 1; }
    100% { opacity: 0; }
}
@-ms-keyframes blink {
    0% {opacity: 1; }
    100% { opacity: 0;}
}
@-o-keyframes blink {
    0% { opacity: 1; }
    100% { opacity: 0; }
}
/* 定义blink类*/
.blink{
    color: #333;
    animation: blink 1s linear infinite;
    /* 其它浏览器兼容性前缀 */
    -webkit-animation: blink 1s linear infinite;
    -moz-animation: blink 1s linear infinite;
    -ms-animation: blink 1s linear infinite;
    -o-animation: blink 1s linear infinite;
}

.list-enter-active, .list-leave-active {
  transition: all 1s;
}
.list-enter, .list-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}
</style>
